package com.jianjun.project.monitor.operlog;

import cn.hutool.core.convert.Convert;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jianjun.common.constant.HttpStatus;
import com.jianjun.framework.web.domain.AjaxResult;
import com.jianjun.framework.web.interceptor.DataScope;
import com.jianjun.framework.web.page.TableDataInfo;
import com.jianjun.framework.web.render.ExcelWriterRender;
import com.jianjun.project.common.model.SysOperLog;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 操作日志记录
 *
 * @author source
 */
@Slf4j
@Path(value = "/monitor/operlog")
public class SysOperlogController extends Controller {
    @Inject
    SysOperLogService operLogService;

    @DataScope(permission = "monitor:operlog:list")
    public void list() {
        SysOperLog sysOperLog = JsonKit.parse(getKv().toJson(), SysOperLog.class);
        Page<SysOperLog> page = operLogService.paginate(sysOperLog);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getList());
        rspData.setTotal(page.getTotalRow());
        renderJson(rspData);
    }

    @DataScope(permission = "monitor:operlog:export")
    public void export() {
        SysOperLog sysOperLog = JsonKit.parse(getKv().toJson(), SysOperLog.class);
        List<SysOperLog> list = operLogService.selectOperLogList(sysOperLog);
        List<Map<String, Object>> mapList = list.stream().map(Model::toMap).collect(Collectors.toList());
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(mapList, true);
        render(new ExcelWriterRender(writer, sysOperLog.getClass().getSimpleName()));
    }

    @DataScope(permission = "monitor:operlog:remove")
    public void index() {
        renderJson(AjaxResult.ajax(operLogService.deleteOperLogByIds(Convert.toLongArray(getPara()))));
    }

    @DataScope(permission = "monitor:operlog:remove")
    public void clean() {
        operLogService.cleanOperLog();
        renderJson(AjaxResult.success());
    }
}
